package com.shangxia.monomer.study.designPatterns.structuralType.flyweight;

import lombok.AllArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ProjectName: monomer
 * @ClassName: FlyweightDemo
 * @Time: 2021/7/20
 * @Author: zhouy
 * @Description:
 * @Experience:
 */

@Slf4j
public class FlyweightDemo {
    /**
     * 利用共享的方式来支持大量细粒度的对象，这些对象一部分内部状态是相同的。
     * 注意共享部分的线程安全 最好是不可变的
     *
     * @param args
     */
    public static void main(String[] args) {
        NodeTree nodeTree1 = new NodeTree(1, 2, TreeFactory.getTree("hhh", "red"));
        NodeTree nodeTree2 = new NodeTree(2, 4, TreeFactory.getTree("hhh", "red"));
        System.out.println(nodeTree1);
        System.out.println(nodeTree2);
    }
}

@AllArgsConstructor
@ToString
class NodeTree {
    private Integer x;
    private Integer y;
    private Tree tree;
}

@AllArgsConstructor
@ToString
class Tree {
    private final String name;
    private final Object data;
}

class TreeFactory {
    private static Map<String, Tree> treeMap = new ConcurrentHashMap<>();

    public static Tree getTree(String name, Object obj) {
        if (treeMap.containsKey(name)) {
            return treeMap.get(name);
        }
        Tree tree = new Tree(name, obj);
        treeMap.put(name, tree);
        return tree;
    }
}
